package com.css.fxfzypg.util;
import com.css.fxfzypg.modules.test.CustomXWPFDocument;
import com.google.code.appengine.awt.Color;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import fr.opensagres.xdocreport.itext.extension.font.IFontProvider;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.UUID;

public class FileUploadUtil {

    /**
     * 上传文件工具类
     *
     * @param uploadFile 文件
     * @param fileDir    文件目录名
     * @param request
     * @return
     */
    public static String uploadUtil(MultipartFile uploadFile, String fileDir, HttpServletRequest request) {
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        long size = uploadFile.getSize();
        Long maxfile = 1024*50*1024l;
        if (size>maxfile)
        {
            return "文件超出50M" ;
        }
        String realPath = fileDir;
        System.out.println("文件上传：" + realPath);
        // String format = "/"+sdf.format(new Date());
        File folder = new File(realPath);
        // 是否目录
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        String filePath = "";
        String oldName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            uploadFile.transferTo(new File(folder, newName));
            filePath = fileDir + "/" + newName;
            return filePath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    public static void download(String path, HttpServletResponse res){
        InputStream fis=null;
        OutputStream toClient=null;
        try {
            //获取下载的路径
            File file=new File(path);
            //获取文件名
            String filename=file.getName();
            //取得文件的后缀名
            String ext=filename.substring(filename.lastIndexOf(".")+1).toUpperCase();
            //以流的形式下载文件
            fis=new BufferedInputStream(new FileInputStream(file));
            System.out.println("文件大小："+fis.available());
            //创建一个和文件一样大小的缓存区
            byte[] buffer=new byte[fis.available()];
            //读取流
            fis.read(buffer);
            //清空首部空白行
            res.reset();
            //设置文件下载后的指定文件名
            res.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("gb2312"),"ISO8859-1"));
            res.addHeader("Content-Length", "" + file.length());
            //response.getOutputStream() 获得字节流，通过该字节流的write(byte[] bytes)可以向response缓冲区中写入字节，再由Tomcat服务器将字节内容组成Http响应返回给浏览器。
            toClient = new BufferedOutputStream(res.getOutputStream());
            res.setContentType("application/octet-stream");
            //将buffer 个字节从指定的 byte 数组写入此输出流。
            toClient.write(buffer);
            //刷新此缓冲的输出流。这迫使所有缓冲的输出字节被写出到底层输出流中。 把缓存区的数据全部写出
            toClient.flush();
        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            try {
                //关闭流
                fis.close();
                //关闭缓冲输出流
                toClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }


    public static void downloadPDF(String path, HttpServletResponse res){
        InputStream fis=null;
        OutputStream os=null;
        try {
            System.out.println(path);
            String pdfPath=path.substring(0,path.lastIndexOf("."))+".pdf";
            File filePdf=new File(pdfPath);
            if (filePdf.exists()){
               // filePdf.delete();
                //获取文件名
                String filename=filePdf.getName();
                res.reset();
                res.setContentType("application/octet-stream");
                res.setHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(filename,"UTF-8") + "\"");
                res.setHeader("Access-Control-Allow-Origin", "*");
                res.setHeader("Access-Control-Allow-Method", "POST,GET");
                fis = new FileInputStream(new File(pdfPath));
                os = res.getOutputStream();
            }
            if (!filePdf.exists()){
                filePdf.createNewFile();
                CustomXWPFDocument doc = new CustomXWPFDocument(new FileInputStream(path));
                OutputStream ops = new FileOutputStream(filePdf);
                PdfOptions options = PdfOptions.create();
/*                options.fontProvider(new IFontProvider() {
                    @Override
                    public Font getFont(String familyName, String encoding, float size, int style, Color color) {
                        try {
                            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                            Font fontChinese = new Font(bfChinese, 12, style, color);
                            if (familyName != null)
                                fontChinese.setFamily(familyName);
                            return fontChinese;
                        } catch (Exception e) {
                            e.printStackTrace();
                            return null;
                        }
                    }
                });*/
                options.fontEncoding("UTF-8");
                PdfConverter.getInstance().convert(doc, ops, options);
                //获取文件名
                String filename=filePdf.getName();
                //取得文件的后缀名
                String ext=filename.substring(filename.lastIndexOf(".")+1).toUpperCase();
                res.reset();
                res.setContentType("application/octet-stream");
                res.setHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(filename,"UTF-8") + "\"");
                res.setHeader("Access-Control-Allow-Origin", "*");
                res.setHeader("Access-Control-Allow-Method", "POST,GET");
                fis = new FileInputStream(new File(pdfPath));
                os = res.getOutputStream();
            }
            int flag = 0;
            while ((flag = fis.read()) != -1) {
                os.write(flag);
            }
        } catch (Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
        } finally{
            try{
                if(fis != null){
                    fis.close();
                }
                if(os != null){
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }





}
